﻿using System;
using System.Threading;
using System.Windows.Forms;
using FBroSharp;              // ⚠️ #1 MOST CRITICAL! FBroSharpControl, FBroSharpBrowserListControl
using FBroSharp.Callback;
using FBroSharp.Const;
using FBroSharp.DataType;
using FBroSharp.Event;
using FBroSharp.Lib;          // ⚠️ CRITICAL! IFBroSharpBrowser, IFBroSharpFrame
using FBroSharp.Value;        // ⚠️ CRITICAL! FBroSharpWindowsInfo, FBroSharpBrowserSetting

namespace 自动登录浏览器
{
    public partial class Form1 : Form
    {
        // 浏览器用户标识
        private const string BROWSER_USER_FLAG = "main_browser";
        
        // 自动登录配置
        private string _loginUrl = "https://example.com/login";
        private string _username = "";
        private string _password = "";
        private string _usernameSelector = "#username";
        private string _passwordSelector = "#password";
        private string _loginButtonSelector = "#login-button";

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {
            Console.WriteLine("=== 窗体加载，开始创建浏览器 ===");
            UpdateStatus("正在初始化浏览器...");
            
            // 创建浏览器
            CreateBrowser();
        }

        /// <summary>
        /// 创建浏览器实例
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // ⚠️ CRITICAL: 使用 FBroSharpWindowsInfo (注意WindowS有's'!)
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // ⚠️ 嵌入式浏览器必需！
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "FBro自动登录浏览器"
                };

                // ⚠️ CRITICAL: 使用 FBroSharpBrowserSetting (单数，无's'!)
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // ⚠️ CRITICAL: event_control 参数必须使用 default，不能用 null (因为是struct!)
                bool success = FBroSharpControl.CreatBrowser(
                    "https://www.baidu.com",  // 初始URL
                    windowInfo,
                    settings,
                    null,  // request_context
                    null,  // extra_info
                    browserEvent,
                    default,  // ⚠️ 使用 default，不是 null!
                    BROWSER_USER_FLAG
                );

                if (success)
                {
                    Console.WriteLine("✅ 浏览器创建请求已提交");
                    UpdateStatus("浏览器创建中...");
                }
                else
                {
                    Console.WriteLine("❌ 浏览器创建失败");
                    UpdateStatus("浏览器创建失败！");
                    MessageBox.Show("浏览器创建失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 创建浏览器异常: {ex.Message}");
                UpdateStatus($"创建失败: {ex.Message}");
                MessageBox.Show($"创建浏览器失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                // 获取浏览器实例
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                
                // ⚠️ CRITICAL: IsValid 是属性，不是方法！
                if (browser != null && browser.IsValid)
                {
                    Console.WriteLine("🔒 关闭浏览器...");
                    browser.CloseBrowser(false, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 关闭浏览器异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 窗体大小调整事件
        /// ⚠️ CRITICAL: 嵌入式浏览器必须处理resize事件！
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                
                // ⚠️ CRITICAL: IsValid 是属性，不是方法！
                if (browser != null && browser.IsValid)
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 访问按钮点击事件
        /// </summary>
        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        /// <summary>
        /// 导航到指定URL
        /// </summary>
        private void NavigateToUrl(string url)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(url))
                {
                    MessageBox.Show("请输入有效的URL！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var frame = browser.GetMainFrame();
                if (frame != null)
                {
                    frame.LoadURL(url);
                    Console.WriteLine($"🔄 导航到: {url}");
                    UpdateStatus($"正在访问: {url}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 导航失败: {ex.Message}");
                MessageBox.Show($"导航失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 自动登录按钮点击事件
        /// </summary>
        private void btnAutoLogin_Click(object sender, EventArgs e)
        {
            if (!ValidateLoginConfig())
            {
                return;
            }

            // 导航到登录页面并等待加载后自动登录
            _loginUrl = txtLoginUrl.Text.Trim();
            _username = txtUsername.Text;
            _password = txtPassword.Text;
            _usernameSelector = txtUsernameSelector.Text.Trim();
            _passwordSelector = txtPasswordSelector.Text.Trim();
            _loginButtonSelector = txtLoginButtonSelector.Text.Trim();

            NavigateToUrl(_loginUrl);
            
            UpdateStatus("正在导航到登录页面...");
        }

        /// <summary>
        /// 开始自动登录（在浏览器加载完成后调用）
        /// </summary>
        public void BeginAutoLogin()
        {
            // 延迟执行，等待页面完全加载
            System.Threading.Tasks.Task.Run(() =>
            {
                Thread.Sleep(2000);  // 等待2秒确保页面加载完成
                
                Invoke(new Action(() =>
                {
                    PerformAutoLogin();
                }));
            });
        }

        /// <summary>
        /// 执行自动登录操作
        /// </summary>
        private void PerformAutoLogin()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                
                if (browser == null || !browser.IsValid)
                {
                    UpdateStatus("浏览器未就绪！");
                    return;
                }

                var frame = browser.GetMainFrame();
                if (frame == null)
                {
                    UpdateStatus("无法获取主框架！");
                    return;
                }

                // 获取当前URL，只在登录页面执行自动登录
                string currentUrl = frame.GetURL();
                if (!currentUrl.Contains(_loginUrl.Replace("https://", "").Replace("http://", "").Split('/')[0]))
                {
                    Console.WriteLine($"当前页面不是登录页面，跳过自动登录。当前URL: {currentUrl}");
                    return;
                }

                if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
                {
                    Console.WriteLine("用户名或密码为空，跳过自动登录");
                    return;
                }

                Console.WriteLine("=== 开始自动登录 ===");
                UpdateStatus("正在自动填写登录信息...");

                // Step 1: 等待页面元素加载
                WaitForElement(_usernameSelector, 5000);

                // Step 2: 填写用户名
                FillInput(_usernameSelector, _username);
                Thread.Sleep(500);

                // Step 3: 填写密码
                FillInput(_passwordSelector, _password);
                Thread.Sleep(500);

                // Step 4: 点击登录按钮
                ClickElement(_loginButtonSelector);

                UpdateStatus("自动登录操作已执行");
                Console.WriteLine("✅ 自动登录操作完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 自动登录失败: {ex.Message}");
                UpdateStatus($"自动登录失败: {ex.Message}");
                MessageBox.Show($"自动登录失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 等待页面元素出现
        /// </summary>
        private void WaitForElement(string selector, int timeoutMs)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid) return;

                var frame = browser.GetMainFrame();
                if (frame == null) return;

                // 使用JavaScript检查元素是否存在
                string script = $@"
                    (function() {{
                        var element = document.querySelector('{selector}');
                        return element !== null;
                    }})();
                ";

                int waited = 0;
                while (waited < timeoutMs)
                {
                    // 执行JavaScript检查元素
                    // 注意：这里简化处理，实际应该使用回调
                    Thread.Sleep(100);
                    waited += 100;
                }

                Console.WriteLine($"✅ 等待元素: {selector}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 等待元素失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 填写输入框
        /// </summary>
        private void FillInput(string selector, string value)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid) return;

                var frame = browser.GetMainFrame();
                if (frame == null) return;

                // 使用JavaScript填写输入框
                string script = $@"
                    (function() {{
                        var element = document.querySelector('{selector}');
                        if (element) {{
                            element.value = '{value.Replace("'", "\\'")}';
                            element.dispatchEvent(new Event('input', {{ bubbles: true }}));
                            element.dispatchEvent(new Event('change', {{ bubbles: true }}));
                            return true;
                        }}
                        return false;
                    }})();
                ";

                frame.ExecuteJavaScript(script, "", 0);
                Console.WriteLine($"✅ 填写输入框: {selector} = {(selector.Contains("password") ? "******" : value)}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 填写输入框失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 点击元素
        /// </summary>
        private void ClickElement(string selector)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid) return;

                var frame = browser.GetMainFrame();
                if (frame == null) return;

                // 使用JavaScript点击元素
                string script = $@"
                    (function() {{
                        var element = document.querySelector('{selector}');
                        if (element) {{
                            element.click();
                            return true;
                        }}
                        return false;
                    }})();
                ";

                frame.ExecuteJavaScript(script, "", 0);
                Console.WriteLine($"✅ 点击元素: {selector}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 点击元素失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查登录状态按钮点击事件
        /// </summary>
        private void btnCheckLogin_Click(object sender, EventArgs e)
        {
            CheckLoginStatus();
        }

        /// <summary>
        /// 检查登录状态
        /// </summary>
        private void CheckLoginStatus()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var frame = browser.GetMainFrame();
                if (frame == null)
                {
                    MessageBox.Show("无法获取主框架！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string currentUrl = frame.GetURL();
                
                // 简单判断：如果不在登录页面，认为已登录
                bool isLoggedIn = !currentUrl.Contains("login");
                
                string message = isLoggedIn 
                    ? $"✅ 已登录\n\n当前URL: {currentUrl}" 
                    : $"❌ 未登录\n\n当前URL: {currentUrl}";
                
                MessageBox.Show(message, "登录状态检查", MessageBoxButtons.OK, 
                    isLoggedIn ? MessageBoxIcon.Information : MessageBoxIcon.Warning);
                
                Console.WriteLine($"登录状态检查: {(isLoggedIn ? "已登录" : "未登录")}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 检查登录状态失败: {ex.Message}");
                MessageBox.Show($"检查失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 保存配置按钮点击事件
        /// </summary>
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            if (ValidateLoginConfig())
            {
                MessageBox.Show("配置已保存！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 验证登录配置
        /// </summary>
        private bool ValidateLoginConfig()
        {
            if (string.IsNullOrWhiteSpace(txtLoginUrl.Text))
            {
                MessageBox.Show("请输入登录页面URL！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLoginUrl.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtUsername.Text))
            {
                MessageBox.Show("请输入用户名！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsername.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MessageBox.Show("请输入密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtUsernameSelector.Text))
            {
                MessageBox.Show("请输入用户名框选择器！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsernameSelector.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtPasswordSelector.Text))
            {
                MessageBox.Show("请输入密码框选择器！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPasswordSelector.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtLoginButtonSelector.Text))
            {
                MessageBox.Show("请输入登录按钮选择器！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLoginButtonSelector.Focus();
                return false;
            }

            return true;
        }

        #region UI更新方法（供BrowserEvent调用）

        /// <summary>
        /// 更新状态栏文本
        /// ⚠️ CRITICAL: 必须是 public，因为BrowserEvent会调用
        /// </summary>
        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }

            lblStatus.Text = message;
        }

        /// <summary>
        /// 更新URL文本框
        /// </summary>
        public void UpdateUrl(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUrl(url)));
                return;
            }

            txtUrl.Text = url;
        }

        /// <summary>
        /// 更新窗体标题
        /// </summary>
        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }

            this.Text = $"{title} - FBro自动登录浏览器";
        }

        /// <summary>
        /// 更新加载状态
        /// </summary>
        public void UpdateLoadingState(bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateLoadingState(isLoading, canGoBack, canGoForward)));
                return;
            }

            lblLoading.Text = isLoading ? "⏳ 加载中..." : "";
        }

        #endregion
    }
}
